package com.edu.glutdataconvertserver.listen;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.edu.glutdataconvertcommon.domain.TGlutDcSkjsxx;
import com.edu.glutdataconvertcommon.domain.TGlutDcXksjlb;
import com.edu.glutdataconvertserver.mapper.auto.TGlutDcXksjlbMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Component
public class GxjxXksjlbReceiver {

    private TGlutDcXksjlbMapper tGlutDcXksjlbMapper;

    @Autowired
    public GxjxXksjlbReceiver(TGlutDcXksjlbMapper tGlutDcXksjlbMapper) {
        this.tGlutDcXksjlbMapper = tGlutDcXksjlbMapper;
    }

    @RabbitListener(queues = "xksjlbQUEUE")
    public void process(@Payload byte[] message, Message message1, Channel channel) throws IOException {
        try {
            String result = new String(message, "utf-8");
            List<TGlutDcXksjlb> tGlutDcXksjlbs = JSONArray.parseArray(result, TGlutDcXksjlb.class);
            System.out.println("DirectReceiver消费者收到消息  : " + JSON.toJSONString(tGlutDcXksjlbs));
            tGlutDcXksjlbMapper.insertList(tGlutDcXksjlbs);
            channel.basicAck(message1.getMessageProperties().getDeliveryTag(), true);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            channel.basicReject(message1.getMessageProperties().getDeliveryTag(), false);
        }
    }
}